#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2013-9-5

@author: iori
'''
from urllib import urlopen

class Video(object):
    def __init__(self, url, filename, **attr):
        self.url = url
        self.filename = filename
        self.__dict__.update(**attr)
        
    def download(self, path='', chunk=8*1024, on_progress=None, on_finish=None):
        proxies = {'http':'http://127.0.0.1:8087'}
        res = urlopen(self.url, proxies = proxies)
        if not path: path = '.'
        if path.endswith('/'): path = path[:-2]
        fpath = '%s/%s.%s'%(path, self.filename, self.extension)
        print 'Begin downloading %s'%self.filename
        with open(fpath, 'wb') as fp:
            meta_data = res.info()
            fsize = int(meta_data.get('Content-Length') or meta_data.get('content-length'))
            buff = ''
            bytes_received = 0
            while True:
                buff = res.read(chunk)
                if not buff:
                    if on_finish:
                        on_finish(fpath)
                    break
                bytes_received += len(buff)
                fp.write(buff)
                if on_progress:
                    on_progress(bytes_received, fsize)
                    
    def __cmp__(self, other):
            res1 = int(self.resolution[:-2]) # remove tail p
            res2 = int(other.resolution[:-2])
            if res1 == res2:
                return cmp(self.extension, other.extension)        
            else:
                return res1 - res2

    def __str__(self):
        return str(self.__dict__)